package com.school.base.action.admin;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.school.base.model.Admin;
import com.school.base.service.AdminService;
import com.school.common.base.BaseAction;
import com.school.common.util.SpringUtils;

/**
 * @author gaobiao
 * 
 */
public class AdminAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8553504869455475627L;
	private static Logger logger = Logger.getLogger(AdminAction.class);
	private static AdminService service = (AdminService) SpringUtils.getBean("base_adminService");
	private Admin admin;
	private List<Admin> adminList;

	public Admin getAdmin() {
		return admin;
	}

	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public List<Admin> getAdminList() {
		return adminList;
	}

	public void setAdminList(List<Admin> adminList) {
		this.adminList = adminList;
	}

	public String list() {
		adminList = service.getAdminList(admin, pageBean);
		return SUCCESS;
	}

	public String edit() {
		if (admin != null && admin.getId() > 0) {
			admin = service.getAdminById(admin.getId());
		}
		return SUCCESS;
	}

	public String editDo() {
		if ("POST".equals(this.getHttpServletRequest().getMethod())) {
			if (admin != null) {
				if (admin.getId() > 0) {
					try {
						service.updateAdmin(admin);
						logger.info("Update admin.");
					} catch (Exception e) {
						this.addActionError(e.getMessage());
						return INPUT;
					}
				} else {
					try {
						service.insertAdmin(admin);
						logger.info("Insert admin.");
					} catch (Exception e) {
						this.addActionError(e.getMessage());
						return INPUT;
					}
				}
			} else {
				logger.info("Not save admin:admin object is null.");
			}
		} else {
			logger.info("Not save admin:the request method is not 'post'.");
		}
		return SUCCESS;
	}

	public String delete() {
		if (admin != null && admin.getId() > 0) {
			service.deleteAdmin(admin.getId());
			logger.info("Delete admin.");
		} else {
			logger.info("Not delete admin:admin object is null.");
		}
		return SUCCESS;
	}

	public void checkLoginName() throws IOException {
		HttpServletResponse response = this.getHttpServletResponse();
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		if (admin != null && admin.getLoginName() != null && !admin.getLoginName().isEmpty()) {
			String str = service.checkLoginName(admin.getLoginName(), admin.getId()) ? "false" : "true";
			response.getWriter().print(str);
		}
		response.getWriter().print("false");
	}
}
